<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class BaseController extends Controller
{
    public $mangerinfo;
    public function __construct(Request $request)
    {
        $token = $request->header('token');
        $utype=$request->header('utype');
        $mangerinfo = Redis::get($token);
        $mangerinfo = $mangerinfo ? json_decode($mangerinfo, true) : '';

        $this->middleware(function ($request, $next) use ($token, $mangerinfo,$utype) { //控制器中间件

            if (isset($mangerinfo['id']) && isset($mangerinfo['cpid'])) {
                // $tokenbyid = Redis::get('manger_user_tokenbyid_' . $mangerinfo['id']);
                // if ($token!=$tokenbyid) {
                //     return response()->json([
                //         'code' => 401, 'msg' => '登录失效，请重新登录!'
                //     ], 200);
                // }
            } else {
                return response()->json([
                    'code' => 401, 'msg' => '登录失效，请重新登录!!'
                ], 200);
            }

            if(!in_array($utype,$mangerinfo['utypes'])){
                return response()->json([
                    'code' => 402, 'msg' => '无效权限组，请重新登录!!'
                ], 200);
            }



            if (is_array($mangerinfo)) {
                // $this->mangerinfo = ['id' => $mangerinfo['id'], 'cpid' => $mangerinfo['cpid'], 'utype' => $mangerinfo['utype'], 'code_no' => $mangerinfo['code_no'], 'pid' => $mangerinfo['pid'], 'realname' => $mangerinfo['realname'], 'mobile' => $mangerinfo['mobile'],'cpd_id'=>$mangerinfo['cpd_id'],'sys_dpm_id'=>$mangerinfo['sys_dpm_id']];
                //$this->mangerinfo = ['id' => $mangerinfo['id'], 'cpid' => $mangerinfo['cpid'], 'utype' => $utype, 'code_no' => $mangerinfo['code_no'], 'pid' => $mangerinfo['pid'], 'realname' => $mangerinfo['realname'], 'mobile' => $mangerinfo['mobile'],'cpd_id'=>$mangerinfo['cpd_id'],'sys_dpm_id'=>$mangerinfo['sys_dpm_id'],'org_id'=>$mangerinfo['org_id']];
                $this->mangerinfo = ['id' => $mangerinfo['id'], 'cpid' => $mangerinfo['cpid'], 'utype' => $utype, 'code_no' => $mangerinfo['code_no'], 'pid' => $mangerinfo['pid'], 'realname' => $mangerinfo['realname'], 'mobile' => $mangerinfo['mobile'],'cpd_id'=>$mangerinfo['cpd_id']??0,'sys_dpm_id'=>$mangerinfo['sys_dpm_id'],'org_id'=>$mangerinfo['org_id']];

            }
            $response=$next($request);
            return $response;
        });
    }
}
